##   protocol.py
##
##   Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov
##
##   This program is free software; you can redistribute it and/or modify
##   it under the terms of the GNU General Public License as published by
##   the Free Software Foundation; either version 2, or (at your option)
##   any later version.
##
##   This program is distributed in the hope that it will be useful,
##   but WITHOUT ANY WARRANTY; without even the implied warranty of
##   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##   GNU General Public License for more details.

# $Id: protocol.py,v 1.60 2009/04/07 11:14:28 snakeru Exp $

"""
Protocol module contains tools that is needed for processing of
xmpp-related data structures.
"""

from simplexml import Node, XML_ls, XMLescape, ustr

import time

NS_ACTIVITY			='http://jabber.org/protocol/activity'					# XEP-0108
NS_ADDRESS			='http://jabber.org/protocol/address'					# XEP-0033
NS_ADMIN			='http://jabber.org/protocol/admin'						# XEP-0133
NS_ADMIN_ADD_USER				=NS_ADMIN+'#add-user'						# XEP-0133
NS_ADMIN_DELETE_USER			=NS_ADMIN+'#delete-user'					# XEP-0133
NS_ADMIN_DISABLE_USER			=NS_ADMIN+'#disable-user'					# XEP-0133
NS_ADMIN_REENABLE_USER			=NS_ADMIN+'#reenable-user'					# XEP-0133
NS_ADMIN_END_USER_SESSION		=NS_ADMIN+'#end-user-session'				# XEP-0133
NS_ADMIN_GET_USER_PASSWORD		=NS_ADMIN+'#get-user-password'				# XEP-0133
NS_ADMIN_CHANGE_USER_PASSWORD	=NS_ADMIN+'#change-user-password'			# XEP-0133
NS_ADMIN_GET_USER_ROSTER		=NS_ADMIN+'#get-user-roster'				# XEP-0133
NS_ADMIN_GET_USER_LASTLOGIN		=NS_ADMIN+'#get-user-lastlogin'				# XEP-0133
NS_ADMIN_USER_STATS				=NS_ADMIN+'#user-stats'						# XEP-0133
NS_ADMIN_EDIT_BLACKLIST			=NS_ADMIN+'#edit-blacklist'					# XEP-0133
NS_ADMIN_EDIT_WHITELIST			=NS_ADMIN+'#edit-whitelist'					# XEP-0133
NS_ADMIN_REGISTERED_USERS_NUM	=NS_ADMIN+'#get-registered-users-num'		# XEP-0133
NS_ADMIN_DISABLED_USERS_NUM		=NS_ADMIN+'#get-disabled-users-num'			# XEP-0133
NS_ADMIN_ONLINE_USERS_NUM		=NS_ADMIN+'#get-online-users-num'			# XEP-0133
NS_ADMIN_ACTIVE_USERS_NUM		=NS_ADMIN+'#get-active-users-num'			# XEP-0133
NS_ADMIN_IDLE_USERS_NUM			=NS_ADMIN+'#get-idle-users-num'				# XEP-0133
NS_ADMIN_REGISTERED_USERS_LIST	=NS_ADMIN+'#get-registered-users-list'		# XEP-0133
NS_ADMIN_DISABLED_USERS_LIST	=NS_ADMIN+'#get-disabled-users-list'		# XEP-0133
NS_ADMIN_ONLINE_USERS_LIST		=NS_ADMIN+'#get-online-users-list'			# XEP-0133
NS_ADMIN_ACTIVE_USERS_LIST		=NS_ADMIN+'#get-active-users-list'			# XEP-0133
NS_ADMIN_IDLE_USERS_LIST		=NS_ADMIN+'#get-idle-users-list'			# XEP-0133
NS_ADMIN_ANNOUNCE				=NS_ADMIN+'#announce'						# XEP-0133
NS_ADMIN_SET_MOTD				=NS_ADMIN+'#set-motd'						# XEP-0133
NS_ADMIN_EDIT_MOTD				=NS_ADMIN+'#edit-motd'						# XEP-0133
NS_ADMIN_DELETE_MOTD			=NS_ADMIN+'#delete-motd'					# XEP-0133
NS_ADMIN_SET_WELCOME			=NS_ADMIN+'#set-welcome'					# XEP-0133
NS_ADMIN_DELETE_WELCOME			=NS_ADMIN+'#delete-welcome'					# XEP-0133
NS_ADMIN_EDIT_ADMIN				=NS_ADMIN+'#edit-admin'						# XEP-0133
NS_ADMIN_RESTART				=NS_ADMIN+'#restart'						# XEP-0133
NS_ADMIN_SHUTDOWN				=NS_ADMIN+'#shutdown'						# XEP-0133
NS_AGENTS			='jabber:iq:agents'										# XEP-0094 (historical)
NS_AMP				='http://jabber.org/protocol/amp'						# XEP-0079
NS_AMP_ERRORS					=NS_AMP+'#errors'							# XEP-0079
NS_AUTH				='jabber:iq:auth'										# XEP-0078
NS_AVATAR			='jabber:iq:avatar'										# XEP-0008 (historical)
NS_BIND				='urn:ietf:params:xml:ns:xmpp-bind'						# RFC 3920
NS_BROWSE			='jabber:iq:browse'										# XEP-0011 (historical)
NS_BYTESTREAM		='http://jabber.org/protocol/bytestreams'				# XEP-0065
NS_CAPS				='http://jabber.org/protocol/caps'						# XEP-0115
NS_CHATSTATES		='http://jabber.org/protocol/chatstates'				# XEP-0085
NS_CLIENT			='jabber:client'										# RFC 3921
NS_COMMANDS			='http://jabber.org/protocol/commands'					# XEP-0050
NS_COMPONENT_ACCEPT	='jabber:component:accept'								# XEP-0114
NS_COMPONENT_1		='http://jabberd.jabberstudio.org/ns/component/1.0'		# Jabberd2
NS_COMPRESS			='http://jabber.org/protocol/compress'					# XEP-0138
NS_DATA				='jabber:x:data'										# XEP-0004
NS_DATA_LAYOUT		='http://jabber.org/protocol/xdata-layout'				# XEP-0141
NS_DATA_VALIDATE	='http://jabber.org/protocol/xdata-validate'			# XEP-0122
NS_DELAY			='jabber:x:delay'										# XEP-0091 (deprecated)
NS_DIALBACK			='jabber:server:dialback'								# RFC 3921
NS_DISCO			='http://jabber.org/protocol/disco'						# XEP-0030
NS_DISCO_INFO					=NS_DISCO+'#info'							# XEP-0030
NS_DISCO_ITEMS					=NS_DISCO+'#items'							# XEP-0030
NS_ENCRYPTED		='jabber:x:encrypted'									# XEP-0027
NS_EVENT			='jabber:x:event'										# XEP-0022 (deprecated)
NS_FEATURE			='http://jabber.org/protocol/feature-neg'				# XEP-0020
NS_FILE				='http://jabber.org/protocol/si/profile/file-transfer'	# XEP-0096
NS_GATEWAY			='jabber:iq:gateway'									# XEP-0100
NS_GEOLOC			='http://jabber.org/protocol/geoloc'					# XEP-0080
NS_GROUPCHAT		='gc-1.0'												# XEP-0045
NS_HTTP_BIND		='http://jabber.org/protocol/httpbind'					# XEP-0124
NS_IBB				='http://jabber.org/protocol/ibb'						# XEP-0047
NS_INVISIBLE		='presence-invisible'									# Jabberd2
NS_IQ				='iq'													# Jabberd2
NS_LAST				='jabber:iq:last'										# XEP-0012
NS_MESSAGE			='message'												# Jabberd2
NS_MOOD				='http://jabber.org/protocol/mood'						# XEP-0107
NS_MUC				='http://jabber.org/protocol/muc'						# XEP-0045
NS_MUC_ADMIN					=NS_MUC+'#admin'							# XEP-0045
NS_MUC_OWNER					=NS_MUC+'#owner'							# XEP-0045
NS_MUC_UNIQUE					=NS_MUC+'#unique'							# XEP-0045
NS_MUC_USER						=NS_MUC+'#user'								# XEP-0045
NS_MUC_REGISTER					=NS_MUC+'#register'							# XEP-0045
NS_MUC_REQUEST					=NS_MUC+'#request'							# XEP-0045
NS_MUC_ROOMCONFIG				=NS_MUC+'#roomconfig'						# XEP-0045
NS_MUC_ROOMINFO					=NS_MUC+'#roominfo'							# XEP-0045
NS_MUC_ROOMS					=NS_MUC+'#rooms'							# XEP-0045
NS_MUC_TRAFIC					=NS_MUC+'#traffic'							# XEP-0045
NS_NICK				='http://jabber.org/protocol/nick'						# XEP-0172
NS_OFFLINE			='http://jabber.org/protocol/offline'					# XEP-0013
NS_PHYSLOC			='http://jabber.org/protocol/physloc'					# XEP-0112
NS_URN_ATTENTION 	= 'urn:xmpp:attention:0'								# XEP-0224
NS_PRESENCE			='presence'												# Jabberd2
NS_PRIVACY			='jabber:iq:privacy'									# RFC 3921
NS_PRIVATE			='jabber:iq:private'									# XEP-0049
NS_PUBSUB			='http://jabber.org/protocol/pubsub'					# XEP-0060
NS_REGISTER			='jabber:iq:register'									# XEP-0077
NS_RC				='http://jabber.org/protocol/rc'						# XEP-0146
NS_ROSTER			='jabber:iq:roster'										# RFC 3921
NS_ROSTERX			='http://jabber.org/protocol/rosterx'					# XEP-0144
NS_RPC				='jabber:iq:rpc'										# XEP-0009
NS_SASL				='urn:ietf:params:xml:ns:xmpp-sasl'						# RFC 3920
NS_SEARCH			='jabber:iq:search'										# XEP-0055
NS_SERVER			='jabber:server'										# RFC 3921
NS_SESSION			='urn:ietf:params:xml:ns:xmpp-session'					# RFC 3921
NS_SI				='http://jabber.org/protocol/si'						# XEP-0096
NS_SI_PUB			='http://jabber.org/protocol/sipub'						# XEP-0137
NS_SIGNED			='jabber:x:signed'										# XEP-0027
NS_STANZAS			='urn:ietf:params:xml:ns:xmpp-stanzas'					# RFC 3920
NS_STREAMS			='http://etherx.jabber.org/streams'						# RFC 3920
NS_TIME				='jabber:iq:time'										# XEP-0090 (deprecated)
NS_TLS				='urn:ietf:params:xml:ns:xmpp-tls'						# RFC 3920
NS_VACATION			='http://jabber.org/protocol/vacation'					# XEP-0109
NS_VCARD			='vcard-temp'											# XEP-0054
NS_VCARD_UPDATE		='vcard-temp:x:update'									# XEP-0153
NS_VERSION			='jabber:iq:version'									# XEP-0092
NS_WAITINGLIST		='http://jabber.org/protocol/waitinglist'				# XEP-0130
NS_XHTML_IM			='http://jabber.org/protocol/xhtml-im'					# XEP-0071
NS_XMPP_STREAMS		='urn:ietf:params:xml:ns:xmpp-streams'					# RFC 3920

NS_STATS			= 'http://jabber.org/protocol/stats'					# XEP-0039
NS_PING				= 'urn:xmpp:ping'										# XEP-0199
NS_MUC_FILTER		= 'http://jabber.ru/muc-filter'
NS_URN_TIME			= 'urn:xmpp:time'										# XEP-0202
NS_RECEIPTS			= 'urn:xmpp:receipts'									# XEP-0184
NS_OOB				= 'jabber:x:oob'										# XEP-0066

STREAM_NOT_AUTHORIZED			= NS_XMPP_STREAMS+" not-authorized"
STREAM_REMOTE_CONNECTION_FAILED	= NS_XMPP_STREAMS+" remote-connection-failed"
SASL_MECHANISM_TOO_WEAK			= NS_SASL+" mechanism-too-weak"
STREAM_XML_NOT_WELL_FORMED		= NS_XMPP_STREAMS+" xml-not-well-formed"
ERR_JID_MALFORMED				= NS_STANZAS+" jid-malformed"
STREAM_SEE_OTHER_HOST			= NS_XMPP_STREAMS+" see-other-host"
STREAM_BAD_NAMESPACE_PREFIX		= NS_XMPP_STREAMS+" bad-namespace-prefix"
ERR_SERVICE_UNAVAILABLE			= NS_STANZAS+" service-unavailable"
STREAM_CONNECTION_TIMEOUT		= NS_XMPP_STREAMS+" connection-timeout"
STREAM_UNSUPPORTED_VERSION		= NS_XMPP_STREAMS+" unsupported-version"
STREAM_IMPROPER_ADDRESSING		= NS_XMPP_STREAMS+" improper-addressing"
STREAM_UNDEFINED_CONDITION		= NS_XMPP_STREAMS+" undefined-condition"
SASL_NOT_AUTHORIZED				= NS_SASL+" not-authorized"
ERR_GONE						= NS_STANZAS+" gone"
SASL_TEMPORARY_AUTH_FAILURE		= NS_SASL+" temporary-auth-failure"
ERR_REMOTE_SERVER_NOT_FOUND		= NS_STANZAS+" remote-server-not-found"
ERR_UNEXPECTED_REQUEST			= NS_STANZAS+" unexpected-request"
ERR_RECIPIENT_UNAVAILABLE		= NS_STANZAS+" recipient-unavailable"
ERR_CONFLICT					= NS_STANZAS+" conflict"
STREAM_SYSTEM_SHUTDOWN			= NS_XMPP_STREAMS+" system-shutdown"
STREAM_BAD_FORMAT				= NS_XMPP_STREAMS+" bad-format"
ERR_SUBSCRIPTION_REQUIRED		= NS_STANZAS+" subscription-required"
STREAM_INTERNAL_SERVER_ERROR	= NS_XMPP_STREAMS+" internal-server-error"
ERR_NOT_AUTHORIZED				= NS_STANZAS+" not-authorized"
SASL_ABORTED					= NS_SASL+" aborted"
ERR_REGISTRATION_REQUIRED		= NS_STANZAS+" registration-required"
ERR_INTERNAL_SERVER_ERROR		= NS_STANZAS+" internal-server-error"
SASL_INCORRECT_ENCODING			= NS_SASL+" incorrect-encoding"
STREAM_HOST_GONE				= NS_XMPP_STREAMS+" host-gone"
STREAM_POLICY_VIOLATION			= NS_XMPP_STREAMS+" policy-violation"
STREAM_INVALID_XML				= NS_XMPP_STREAMS+" invalid-xml"
STREAM_CONFLICT					= NS_XMPP_STREAMS+" conflict"
STREAM_RESOURCE_CONSTRAINT		= NS_XMPP_STREAMS+" resource-constraint"
STREAM_UNSUPPORTED_ENCODING		= NS_XMPP_STREAMS+" unsupported-encoding"
ERR_NOT_ALLOWED					= NS_STANZAS+" not-allowed"
ERR_ITEM_NOT_FOUND				= NS_STANZAS+" item-not-found"
ERR_NOT_ACCEPTABLE				= NS_STANZAS+" not-acceptable"
STREAM_INVALID_FROM				= NS_XMPP_STREAMS+" invalid-from"
ERR_FEATURE_NOT_IMPLEMENTED		= NS_STANZAS+" feature-not-implemented"
ERR_BAD_REQUEST					= NS_STANZAS+" bad-request"
STREAM_INVALID_ID				= NS_XMPP_STREAMS+" invalid-id"
STREAM_HOST_UNKNOWN				= NS_XMPP_STREAMS+" host-unknown"
ERR_UNDEFINED_CONDITION			= NS_STANZAS+" undefined-condition"
SASL_INVALID_MECHANISM			= NS_SASL+" invalid-mechanism"
STREAM_RESTRICTED_XML			= NS_XMPP_STREAMS+" restricted-xml"
ERR_RESOURCE_CONSTRAINT			= NS_STANZAS+" resource-constraint"
ERR_REMOTE_SERVER_TIMEOUT		= NS_STANZAS+" remote-server-timeout"
SASL_INVALID_AUTHZID			= NS_SASL+" invalid-authzid"
ERR_PAYMENT_REQUIRED			= NS_STANZAS+" payment-required"
STREAM_INVALID_NAMESPACE		= NS_XMPP_STREAMS+" invalid-namespace"
ERR_REDIRECT					= NS_STANZAS+" redirect"
STREAM_UNSUPPORTED_STANZA_TYPE	= NS_XMPP_STREAMS+" unsupported-stanza-type"
ERR_FORBIDDEN					= NS_STANZAS+" forbidden"

ERRORS = {
	"urn:ietf:params:xml:ns:xmpp-sasl not-authorized": ['', '', 'The authentication failed because the initiating entity did not provide valid credentials (this includes but is not limited to the case of an unknown username); sent in reply to a <response/> element or an <auth/> element with initial response data.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas payment-required": ['402', 'auth', 'The requesting entity is not authorized to access the requested service because payment is required.'],
	"urn:ietf:params:xml:ns:xmpp-sasl mechanism-too-weak": ['', '', 'The mechanism requested by the initiating entity is weaker than server policy permits for that initiating entity; sent in reply to a <response/> element or an <auth/> element with initial response data.'],
	"urn:ietf:params:xml:ns:xmpp-streams unsupported-encoding": ['', '', 'The initiating entity has encoded the stream in an encoding that is not supported by the server.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas remote-server-timeout": ['504', 'wait', 'A remote server or service specified as part or all of the JID of the intended recipient could not be contacted within a reasonable amount of time.'],
	"urn:ietf:params:xml:ns:xmpp-streams remote-connection-failed": ['', '', 'The server is unable to properly connect to a remote resource that is required for authentication or authorization.'],
	"urn:ietf:params:xml:ns:xmpp-streams restricted-xml": ['', '', 'The entity has attempted to send restricted XML features such as a comment, processing instruction, DTD, entity reference, or unescaped character.'],
	"urn:ietf:params:xml:ns:xmpp-streams see-other-host": ['', '', 'The server will not provide service to the initiating entity but is redirecting traffic to another host.'],
	"urn:ietf:params:xml:ns:xmpp-streams xml-not-well-formed": ['', '', 'The initiating entity has sent XML that is not well-formed.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas subscription-required": ['407', 'auth', 'The requesting entity is not authorized to access the requested service because a subscription is required.'],
	"urn:ietf:params:xml:ns:xmpp-streams internal-server-error": ['', '', 'The server has experienced a misconfiguration or an otherwise-undefined internal error that prevents it from servicing the stream.'],
	"urn:ietf:params:xml:ns:xmpp-sasl invalid-mechanism": ['', '', 'The initiating entity did not provide a mechanism or requested a mechanism that is not supported by the receiving entity; sent in reply to an <auth/> element.'],
	"urn:ietf:params:xml:ns:xmpp-streams policy-violation": ['', '', 'The entity has violated some local service policy.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas conflict": ['409', 'cancel', 'Access cannot be granted because an existing resource or session exists with the same name or address.'],
	"urn:ietf:params:xml:ns:xmpp-streams unsupported-stanza-type": ['', '', 'The initiating entity has sent a first-level child of the stream that is not supported by the server.'],
	"urn:ietf:params:xml:ns:xmpp-sasl incorrect-encoding": ['', '', 'The data provided by the initiating entity could not be processed because the [BASE64]Josefsson, S., The Base16, Base32, and Base64 Data Encodings, July 2003. encoding is incorrect (e.g., because the encoding does not adhere to the definition in Section 3 of [BASE64]Josefsson, S., The Base16, Base32, and Base64 Data Encodings, July 2003.); sent in reply to a <response/> element or an <auth/> element with initial response data.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas registration-required": ['407', 'auth', 'The requesting entity is not authorized to access the requested service because registration is required.'],
	"urn:ietf:params:xml:ns:xmpp-streams invalid-id": ['', '', 'The stream ID or dialback ID is invalid or does not match an ID previously provided.'],
	"urn:ietf:params:xml:ns:xmpp-sasl invalid-authzid": ['', '', 'The authzid provided by the initiating entity is invalid, either because it is incorrectly formatted or because the initiating entity does not have permissions to authorize that ID; sent in reply to a <response/> element or an <auth/> element with initial response data.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas bad-request": ['400', 'modify', 'The sender has sent XML that is malformed or that cannot be processed.'],
	"urn:ietf:params:xml:ns:xmpp-streams not-authorized": ['', '', 'The entity has attempted to send data before the stream has been authenticated, or otherwise is not authorized to perform an action related to stream negotiation.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas forbidden": ['403', 'auth', 'The requesting entity does not possess the required permissions to perform the action.'],
	"urn:ietf:params:xml:ns:xmpp-sasl temporary-auth-failure": ['', '', 'The authentication failed because of a temporary error condition within the receiving entity; sent in reply to an <auth/> element or <response/> element.'],
	"urn:ietf:params:xml:ns:xmpp-streams invalid-namespace": ['', '', 'The streams namespace name is something other than "http://etherx.jabber.org/streams" or the dialback namespace name is something other than "jabber:server:dialback".'],
	"urn:ietf:params:xml:ns:xmpp-stanzas feature-not-implemented": ['501', 'cancel', 'The feature requested is not implemented by the recipient or server and therefore cannot be processed.'],
	"urn:ietf:params:xml:ns:xmpp-streams invalid-xml": ['', '', 'The entity has sent invalid XML over the stream to a server that performs validation.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas item-not-found": ['404', 'cancel', 'The addressed JID or item requested cannot be found.'],
	"urn:ietf:params:xml:ns:xmpp-streams host-gone": ['', '', "The value of the 'to' attribute provided by the initiating entity in the stream header corresponds to a hostname that is no longer hosted by the server."],
	"urn:ietf:params:xml:ns:xmpp-stanzas recipient-unavailable": ['404', 'wait', 'The intended recipient is temporarily unavailable.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas not-acceptable": ['406', 'cancel', 'The recipient or server understands the request but is refusing to process it because it does not meet criteria defined by the recipient or server.'],
	"urn:ietf:params:xml:ns:xmpp-streams invalid-from": ['cancel', '', "The JID or hostname provided in a 'from' address does not match an authorized JID or validated domain negotiated between servers via SASL or dialback, or between a client and a server via authentication and resource authorization."],
	"urn:ietf:params:xml:ns:xmpp-streams bad-format": ['', '', 'The entity has sent XML that cannot be processed.'],
	"urn:ietf:params:xml:ns:xmpp-streams resource-constraint": ['', '', 'The server lacks the system resources necessary to service the stream.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas undefined-condition": ['500', '', ''],
	"urn:ietf:params:xml:ns:xmpp-stanzas redirect": ['302', 'modify', 'The recipient or server is redirecting requests for this information to another entity.'],
	"urn:ietf:params:xml:ns:xmpp-streams bad-namespace-prefix": ['', '', 'The entity has sent a namespace prefix that is unsupported, or has sent no namespace prefix on an element that requires such a prefix.'],
	"urn:ietf:params:xml:ns:xmpp-streams system-shutdown": ['', '', 'The server is being shut down and all active streams are being closed.'],
	"urn:ietf:params:xml:ns:xmpp-streams conflict": ['', '', 'The server is closing the active stream for this entity because a new stream has been initiated that conflicts with the existing stream.'],
	"urn:ietf:params:xml:ns:xmpp-streams connection-timeout": ['', '', 'The entity has not generated any traffic over the stream for some period of time.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas jid-malformed": ['400', 'modify', "The value of the 'to' attribute in the sender's stanza does not adhere to the syntax defined in Addressing Scheme."],
	"urn:ietf:params:xml:ns:xmpp-stanzas resource-constraint": ['500', 'wait', 'The server or recipient lacks the system resources necessary to service the request.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas remote-server-not-found": ['404', 'cancel', 'A remote server or service specified as part or all of the JID of the intended recipient does not exist.'],
	"urn:ietf:params:xml:ns:xmpp-streams unsupported-version": ['', '', "The value of the 'version' attribute provided by the initiating entity in the stream header specifies a version of XMPP that is not supported by the server."],
	"urn:ietf:params:xml:ns:xmpp-streams host-unknown": ['', '', "The value of the 'to' attribute provided by the initiating entity in the stream header does not correspond to a hostname that is hosted by the server."],
	"urn:ietf:params:xml:ns:xmpp-stanzas unexpected-request": ['400', 'wait', 'The recipient or server understood the request but was not expecting it at this time (e.g., the request was out of order).'],
	"urn:ietf:params:xml:ns:xmpp-streams improper-addressing": ['', '', "A stanza sent between two servers lacks a 'to' or 'from' attribute (or the attribute has no value)."],
	"urn:ietf:params:xml:ns:xmpp-stanzas not-allowed": ['405', 'cancel', 'The recipient or server does not allow any entity to perform the action.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas internal-server-error": ['500', 'wait', 'The server could not process the stanza because of a misconfiguration or an otherwise-undefined internal server error.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas gone": ['302', 'modify', 'The recipient or server can no longer be contacted at this address.'],
	"urn:ietf:params:xml:ns:xmpp-streams undefined-condition": ['', '', 'The error condition is not one of those defined by the other conditions in this list.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas service-unavailable": ['503', 'cancel', 'The server or recipient does not currently provide the requested service.'],
	"urn:ietf:params:xml:ns:xmpp-stanzas not-authorized": ['401', 'auth', 'The sender must provide proper credentials before being allowed to perform the action, or has provided improper credentials.'],
	"urn:ietf:params:xml:ns:xmpp-sasl aborted": ['', '', 'The receiving entity acknowledges an <abort/> element sent by the initiating entity; sent in reply to the <abort/> element.']
			}

_errorcodes = {
	'302': 'redirect', # 0
	'400': 'unexpected-request', # 1
	'401': 'not-authorized', # 2
	'402': 'payment-required', # 3
	'403': 'forbidden', # 4
	'404': 'remote-server-not-found', # 5
	'405': 'not-allowed', # 6
	'406': 'not-acceptable', # 7
	'407': 'subscription-required', # 8
	'409': 'conflict', # 9
	'500': 'undefined-condition', # 10
	'501': 'feature-not-implemented', # 11
	'503': 'service-unavailable', # 12
	'504': 'remote-server-timeout' # 13
		}

isResultNode = lambda node: (node and node.getType()=='result')
""" Returns true if the node is a positive reply. """
isGetNode = lambda node: (node and node.getType()=='get')
""" Returns true if the node is a positive reply. """
isSetNode = lambda node: (node and node.getType()=='set')
""" Returns true if the node is a positive reply. """
isErrorNode = lambda node: (node and node.getType()=='error')
""" Returns true if the node is a negative reply. """

class NodeProcessed(Exception):
	""" Exception that should be raised by handler when the handling should be stopped. """
class StreamError(Exception):
	""" Base exception class for stream errors."""
class BadFormat(StreamError): pass
class BadNamespacePrefix(StreamError): pass
class Conflict(StreamError): pass
class ConnectionTimeout(StreamError): pass
class HostGone(StreamError): pass
class HostUnknown(StreamError): pass
class ImproperAddressing(StreamError): pass
class InternalServerError(StreamError): pass
class InvalidFrom(StreamError): pass
class InvalidID(StreamError): pass
class InvalidNamespace(StreamError): pass
class InvalidXML(StreamError): pass
class NotAuthorized(StreamError): pass
class PolicyViolation(StreamError): pass
class RemoteConnectionFailed(StreamError): pass
class ResourceConstraint(StreamError): pass
class RestrictedXML(StreamError): pass
class SeeOtherHost(StreamError): pass
class SystemShutdown(StreamError): pass
class UndefinedCondition(StreamError): pass
class UnsupportedEncoding(StreamError): pass
class UnsupportedStanzaType(StreamError): pass
class UnsupportedVersion(StreamError): pass
class XMLNotWellFormed(StreamError): pass

stream_exceptions = {
	'bad-format': BadFormat,
	'bad-namespace-prefix': BadNamespacePrefix,
	'conflict': Conflict,
	'connection-timeout': ConnectionTimeout,
	'host-gone': HostGone,
	'host-unknown': HostUnknown,
	'improper-addressing': ImproperAddressing,
	'internal-server-error': InternalServerError,
	'invalid-from': InvalidFrom,
	'invalid-id': InvalidID,
	'invalid-namespace': InvalidNamespace,
	'invalid-xml': InvalidXML,
	'not-authorized': NotAuthorized,
	'policy-violation': PolicyViolation,
	'remote-connection-failed': RemoteConnectionFailed,
	'resource-constraint': ResourceConstraint,
	'restricted-xml': RestrictedXML,
	'see-other-host': SeeOtherHost,
	'system-shutdown': SystemShutdown,
	'undefined-condition': UndefinedCondition,
	'unsupported-encoding': UnsupportedEncoding,
	'unsupported-stanza-type': UnsupportedStanzaType,
	'unsupported-version': UnsupportedVersion,
	'xml-not-well-formed': XMLNotWellFormed
					 }

class JID:
	""" JID object. JID can be built from string, modified, compared, serialised into string. """
	def __init__(self, jid=None, node='', domain='', resource=''):
		""" Constructor. JID can be specified as string (jid argument) or as separate parts.
			Examples:
			JID('node@domain/resource')
			JID(node='node',domain='domain.org')
		"""
		if not jid and not domain: raise ValueError('JID must contain at least domain name')
		elif type(jid)==type(self): self.node,self.domain,self.resource=jid.node,jid.domain,jid.resource
		elif domain: self.node,self.domain,self.resource=node,domain,resource
		else:
			if jid.find('@')+1: self.node,jid=jid.split('@',1)
			else: self.node=''
			if jid.find('/')+1: self.domain,self.resource=jid.split('/',1)
			else: self.domain,self.resource=jid,''
	getNode = lambda self: self.node
	""" Return the node part of the JID """
	def setNode(self,node):
		""" Set the node part of the JID to new value. Specify None to remove the node part."""
		self.node=node.lower()
	getDomain = lambda self: self.domain
	""" Return the domain part of the JID """
	def setDomain(self,domain):
		""" Set the domain part of the JID to new value."""
		self.domain=domain.lower()
	getResource = lambda self: self.resource
	""" Return the resource part of the JID """
	def setResource(self,resource):
		""" Set the resource part of the JID to new value. Specify None to remove the resource part."""
		self.resource=resource
	getStripped = lambda self: self.__str__(0)
	""" Return the bare representation of JID. I.e. string value w/o resource. """
	def __eq__(self, other):
		""" Compare the JID to another instance or to string for equality. """
		try: other=JID(other)
		except ValueError: return 0
		return self.resource==other.resource and self.__str__(0) == other.__str__(0)
	__ne__ = lambda self, other: not self.__eq__(other)
	""" Compare the JID to another instance or to string for non-equality. """
	bareMatch = lambda self, other: self.__str__(0) == JID(other).__str__(0)
	""" Compare the node and domain parts of the JID's for equality. """
	def __str__(self,wresource=1):
		""" Serialise JID into string. """
		if self.node: jid=self.node+'@'+self.domain
		else: jid=self.domain
		if wresource and self.resource: return jid+'/'+self.resource
		return jid
	__hash__ = lambda self: hash(self.__str__())
	""" Produce hash of the JID, Allows to use JID objects as keys of the dictionary. """

class Protocol(Node):
	""" A "stanza" object class. Contains methods that are common for presences, iqs and messages. """
	def __init__(self, name=None, to=None, typ=None, frm=None, attrs={}, payload=[], timestamp=None, xmlns=None, node=None):
		""" Constructor, name is the name of the stanza i.e. 'message' or 'presence' or 'iq'.
			to is the value of 'to' attribure, 'typ' - 'type' attribute
			frn - from attribure, attrs - other attributes mapping, payload - same meaning as for simplexml payload definition
			timestamp - the time value that needs to be stamped over stanza
			xmlns - namespace of top stanza node
			node - parsed or unparsed stana to be taken as prototype.
		"""
		if not attrs: attrs={}
		if to: attrs['to']=to
		if frm: attrs['from']=frm
		if typ: attrs['type']=typ
		Node.__init__(self, tag=name, attrs=attrs, payload=payload, node=node)
		if not node and xmlns: self.setNamespace(xmlns)
		if self['to']: self.setTo(self['to'])
		if self['from']: self.setFrom(self['from'])
		if node and type(self)==type(node) and self.__class__==node.__class__ and self.attrs.has_key('id'): del self.attrs['id']
		self.timestamp=None
		for x in self.getTags('x',namespace=NS_DELAY):
			try:
				if not self.getTimestamp() or x.getAttr('stamp')<self.getTimestamp(): self.setTimestamp(x.getAttr('stamp'))
			except: pass
		if timestamp is not None: self.setTimestamp(timestamp)  # To auto-timestamp stanza just pass timestamp=''
	def getTo(self):
		""" Return value of the 'to' attribute. """
		try: return self['to']
		except: return None
	def getFrom(self):
		""" Return value of the 'from' attribute. """
		try: return self['from']
		except: return None
	getTimestamp = lambda self: self.timestamp
	""" Return the timestamp in the 'yyyymmddThhmmss' format. """
	getID = lambda self: self.getAttr('id')
	""" Return the value of the 'id' attribute. """
	setTo = lambda self, val: self.setAttr('to', JID(val))
	""" Set the value of the 'to' attribute. """
	getType = lambda self: self.getAttr('type')
	""" Return the value of the 'type' attribute. """
	setFrom = lambda self, val: self.setAttr('from', JID(val))
	""" Set the value of the 'from' attribute. """
	setType = lambda self, val: self.setAttr('type', val)
	""" Set the value of the 'type' attribute. """
	setID = lambda self, val: self.setAttr('id', val)
	""" Set the value of the 'id' attribute. """
	def getError(self):
		""" Return the error-condition (if present) or the textual description of the error (otherwise). """
		errtag=self.getTag('error')
		if errtag:
			for tag in errtag.getChildren():
				if tag.getName()<>'text': return tag.getName()
			return errtag.getData()
	getErrorCode = lambda self: self.getTagAttr('error','code')
	""" Return the error code. Obsolette. """
	def setError(self,error,code=None):
		""" Set the error code. Obsolette. Use error-conditions instead. """
		if code:
			if str(code) in _errorcodes.keys(): error=ErrorNode(_errorcodes[str(code)],text=error)
			else: error=ErrorNode(ERR_UNDEFINED_CONDITION,code=code,typ='cancel',text=error)
		elif type(error) in [type(''),type(u'')]: error=ErrorNode(error)
		self.setType('error')
		self.addChild(node=error)
	def setTimestamp(self,val=None):
		"""Set the timestamp. timestamp should be the yyyymmddThhmmss string."""
		if not val: val=time.strftime('%Y%m%dT%H:%M:%S', time.gmtime())
		self.timestamp=val
		self.setTag('x',{'stamp':self.timestamp},namespace=NS_DELAY)
	def getProperties(self):
		""" Return the list of namespaces to which belongs the direct childs of element"""
		props=[]
		for child in self.getChildren():
			prop=child.getNamespace()
			if prop not in props: props.append(prop)
		return props
	def __setitem__(self,item,val):
		""" Set the item 'item' to the value 'val'."""
		if item in ['to','from']: val=JID(val)
		return self.setAttr(item,val)

class Message(Protocol):
	""" XMPP Message stanza - "push" mechanism."""
	def __init__(self, to=None, body=None, typ=None, subject=None, attrs={}, frm=None, payload=[], timestamp=None, xmlns=NS_CLIENT, node=None):
		""" Create message object. You can specify recipient, text of message, type of message
			any additional attributes, sender of the message, any additional payload (f.e. jabber:x:delay element) and namespace in one go.
			Alternatively you can pass in the other XML object as the 'node' parameted to replicate it as message. """
		Protocol.__init__(self, 'message', to=to, typ=typ, attrs=attrs, frm=frm, payload=payload, timestamp=timestamp, xmlns=xmlns, node=node)
		if body: self.setBody(body)
		if subject: self.setSubject(subject)
	getBody = lambda self: self.getTagData('body')
	""" Returns text of the message. """
	getSubject = lambda self: self.getTagData('subject')
	""" Returns subject of the message. """
	getThread = lambda self: self.getTagData('thread')
	""" Returns thread of the message. """
	setBody = lambda self, val: self.setTagData('body', val)
	""" Sets the text of the message. """
	setSubject = lambda self,val: self.setTagData('subject', val)
	""" Sets the subject of the message. """
	setThread = lambda self, val: self.setTagData('thread',val)
	""" Sets the thread of the message. """
	def buildReply(self,text=None):
		""" Builds and returns another message object with specified text.
			The to, from and thread properties of new message are pre-set as reply to this message. """
		m=Message(to=self.getFrom(),frm=self.getTo(),body=text)
		th=self.getThread()
		if th: m.setThread(th)
		return m

class Presence(Protocol):
	""" XMPP Presence object."""
	def __init__(self, to=None, typ=None, priority=None, show=None, status=None, attrs={}, frm=None, timestamp=None, payload=[], xmlns=NS_CLIENT, node=None):
		""" Create presence object. You can specify recipient, type of message, priority, show and status values
			any additional attributes, sender of the presence, timestamp, any additional payload (f.e. jabber:x:delay element) and namespace in one go.
			Alternatively you can pass in the other XML object as the 'node' parameted to replicate it as presence. """
		Protocol.__init__(self, 'presence', to=to, typ=typ, attrs=attrs, frm=frm, payload=payload, timestamp=timestamp, xmlns=xmlns, node=node)
		if priority: self.setPriority(priority)
		if show: self.setShow(show)
		if status: self.setStatus(status)
	getPriority = lambda self: self.getTagData('priority')
	""" Returns the priority of the message. """
	getShow = lambda self: self.getTagData('show')
	""" Returns the show value of the message. """
	getStatus = lambda self: self.getTagData('status')
	""" Returns the status string of the message. """
	setPriority = lambda self, val: self.setTagData('priority',val)
	""" Sets the priority of the message. """
	setShow = lambda self, val: self.setTagData('show',val)
	""" Sets the show value of the message. """
	setStatus = lambda self, val: self.setTagData('status',val)
	""" Sets the status string of the message. """

	def _muc_getItemAttr(self,tag,attr):
		for xtag in self.getTags('x',namespace=NS_MUC_USER):
			for child in xtag.getTags(tag):
				return child.getAttr(attr)
	def _muc_getSubTagDataAttr(self,tag,attr):
		for xtag in self.getTags('x',namespace=NS_MUC_USER):
			for child in xtag.getTags('item'):
				for cchild in child.getTags(tag):
					return cchild.getData(),cchild.getAttr(attr)
		return None,None
	getRole = lambda self: self._muc_getItemAttr('item','role')
	"""Returns the presence role (for groupchat)"""
	getAffiliation = lambda self: self._muc_getItemAttr('item','affiliation')
	"""Returns the presence affiliation (for groupchat)"""
	getNick = lambda self: self._muc_getItemAttr('item','nick')
	"""Returns the nick value (for nick change in groupchat)"""
	getJid = lambda self: self._muc_getItemAttr('item','jid')
	"""Returns the presence jid (for groupchat)"""
	getReason = lambda self: self._muc_getSubTagDataAttr('reason','')[0]
	"""Returns the reason of the presence (for groupchat)"""
	getActor = lambda self: self._muc_getSubTagDataAttr('actor','jid')[1]
	"""Returns the reason of the presence (for groupchat)"""
	getStatusCode = lambda self: self._muc_getItemAttr('status','code')
	"""Returns the status code of the presence (for groupchat)"""

class Iq(Protocol):
	""" XMPP Iq object - get/set dialog mechanism. """
	def __init__(self, typ=None, queryNS=None, attrs={}, to=None, frm=None, payload=[], xmlns=NS_CLIENT, node=None):
		""" Create Iq object. You can specify type, query namespace
			any additional attributes, recipient of the iq, sender of the iq, any additional payload (f.e. jabber:x:data node) and namespace in one go.
			Alternatively you can pass in the other XML object as the 'node' parameted to replicate it as an iq. """
		Protocol.__init__(self, 'iq', to=to, typ=typ, attrs=attrs, frm=frm, xmlns=xmlns, node=node)
		if payload: self.setQueryPayload(payload)
		if queryNS: self.setQueryNS(queryNS)
	def getQueryNS(self):
		""" Return the namespace of the 'query' child element."""
		tag=self.getTag('query')
		if tag: return tag.getNamespace()
	def getQuerynode(self):
		""" Return the 'node' attribute value of the 'query' child element."""
		return self.getTagAttr('query','node')
	def getQueryPayload(self):
		""" Return the 'query' child element payload."""
		tag=self.getTag('query')
		if tag: return tag.getPayload()
	def getQueryChildren(self):
		""" Return the 'query' child element child nodes."""
		tag=self.getTag('query')
		if tag: return tag.getChildren()
	setQueryNS = lambda self, namespace: self.setTag('query').setNamespace(namespace)
	""" Set the namespace of the 'query' child element."""
	setQueryPayload = lambda self, payload: self.setTag('query').setPayload(payload)
	""" Set the 'query' child element payload."""
	setQuerynode = lambda self, node: self.setTagAttr('query','node',node)
	""" Set the 'node' attribute value of the 'query' child element."""
	def buildReply(self,typ):
		""" Builds and returns another Iq object of specified type.
			The to, from and query child node of new Iq are pre-set as reply to this Iq. """
		iq=Iq(typ,to=self.getFrom(),frm=self.getTo(),attrs={'id':self.getID()})
		if self.getTag('query'): iq.setQueryNS(self.getQueryNS())
		return iq

class ErrorNode(Node):
	""" XMPP-style error element.
		In the case of stanza error should be attached to XMPP stanza.
		In the case of stream-level errors should be used separately. """
	def __init__(self,name,code=None,typ=None,text=None):
		""" Create new error node object.
			Mandatory parameter: name - name of error condition.
			Optional parameters: code, typ, text. Used for backwards compartibility with older jabber protocol."""
		if ERRORS.has_key(name):
			cod,type,txt=ERRORS[name]
			ns=name.split()[0]
		else: cod,ns,type,txt='500',NS_STANZAS,'cancel',''
		if typ: type=typ
		if code: cod=code
		if text: txt=text
		Node.__init__(self,'error',{},[Node(name)])
		if type: self.setAttr('type',type)
		if not cod: self.setName('stream:error')
		if txt: self.addChild(node=Node(ns+' text',{},[txt]))
		if cod: self.setAttr('code',cod)

class Error(Protocol):
	""" Used to quickly transform received stanza into error reply."""
	def __init__(self,node,error,reply=1):
		""" Create error reply basing on the received 'node' stanza and the 'error' error condition.
			If the 'node' is not the received stanza but locally created ('to' and 'from' fields needs not swapping)
			specify the 'reply' argument as false."""
		if reply: Protocol.__init__(self,to=node.getFrom(),frm=node.getTo(),node=node)
		else: Protocol.__init__(self,node=node)
		self.setError(error)
		if node.getType()=='error': self.__str__=self.__dupstr__
	def __dupstr__(self,dup1=None,dup2=None):
		""" Dummy function used as preventor of creating error node in reply to error node.
			I.e. you will not be able to serialise "double" error into string.
		"""
		return ''

class DataField(Node):
	""" This class is used in the DataForm class to describe the single data item.
		If you are working with jabber:x:data (XEP-0004, XEP-0068, XEP-0122)
		then you will need to work with instances of this class. """
	def __init__(self,name=None,value=None,typ=None,required=0,label=None,desc=None,options=[],node=None):
		""" Create new data field of specified name,value and type.
			Also 'required','desc' and 'options' fields can be set.
			Alternatively other XML object can be passed in as the 'node' parameted to replicate it as a new datafiled.
			"""
		Node.__init__(self,'field',node=node)
		if name: self.setVar(name)
		if type(value) in [list,tuple]: self.setValues(value)
		elif value: self.setValue(value)
		if typ: self.setType(typ)
		elif not typ and not node: self.setType('text-single')
		if required: self.setRequired(required)
		if label: self.setLabel(label)
		if desc: self.setDesc(desc)
		if options: self.setOptions(options)
	def setRequired(self,req=1):
		""" Change the state of the 'required' flag. """
		if req: self.setTag('required')
		else:
			try: self.delChild('required')
			except ValueError: return
	isRequired = lambda self: self.getTag('required')
	""" Returns in this field a required one. """
	setLabel = lambda self, label: self.setAttr('label',label)
	""" Set the label of this field. """
	getLabel = lambda self: self.getAttr('label')
	""" Return the label of this field. """
	setDesc = lambda self, desc: self.setTagData('desc',desc)
	""" Set the description of this field. """
	getDesc = lambda self: self.getTagData('desc')
	""" Return the description of this field. """
	setValue = lambda self, val: self.setTagData('value', val)
	""" Set the value of this field. """
	getValue = lambda self: self.getTagData('value')
	def setValues(self, lst):
		""" Set the values of this field as values-list.
			Replaces all previous filed values! If you need to just add a value - use addValue method."""
		while self.getTag('value'): self.delChild('value')
		for val in lst: self.addValue(val)
	addValue = lambda self, val: self.addChild('value',{},[val])
	""" Add one more value to this field. Used in 'get' iq's or such."""
	def getValues(self):
		""" Return the list of values associated with this field."""
		ret=[]
		for tag in self.getTags('value'): ret.append(tag.getData())
		return ret
	def getOptions(self):
		""" Return label-option pairs list associated with this field."""
		ret=[]
		for tag in self.getTags('option'): ret.append([tag.getAttr('label'),tag.getTagData('value')])
		return ret
	def setOptions(self,lst):
		""" Set label-option pairs list associated with this field."""
		while self.getTag('option'): self.delChild('option')
		for opt in lst: self.addOption(opt)
	def addOption(self,opt):
		""" Add one more label-option pair to this field."""
		if type(opt) in [str,unicode]: self.addChild('option').setTagData('value',opt)
		else: self.addChild('option',{'label':opt[0]}).setTagData('value',opt[1])
	getType = lambda self: self.getAttr('type')
	""" Get type of this field. """
	setType = lambda self, val: self.setAttr('type',val)
	""" Set type of this field. """
	getVar = lambda self: self.getAttr('var')
	""" Get 'var' attribute value of this field. """
	setVar = lambda self, val: self.setAttr('var',val)
	""" Set 'var' attribute value of this field. """

class DataReported(Node):
	""" This class is used in the DataForm class to describe the 'reported data field' data items which are used in
		'multiple item form results' (as described in XEP-0004).
		Represents the fields that will be returned from a search. This information is useful when
		you try to use the jabber:iq:search namespace to return dynamic form information.
		"""
	def __init__(self,node=None):
		""" Create new empty 'reported data' field. However, note that, according XEP-0004:
			* It MUST contain one or more DataFields.
			* Contained DataFields SHOULD possess a 'type' and 'label' attribute in addition to 'var' attribute
			* Contained DataFields SHOULD NOT contain a <value/> element.
			Alternatively other XML object can be passed in as the 'node' parameted to replicate it as a new
			dataitem.
		"""
		Node.__init__(self,'reported',node=node)
		if node:
			newkids=[]
			for n in self.getChildren():
				if	n.getName()=='field': newkids.append(DataField(node=n))
				else: newkids.append(n)
			self.kids=newkids
	getField = lambda self, name: self.getTag('field',attrs={'var':name})
	""" Return the datafield object with name 'name' (if exists). """
	def setField(self,name,typ=None,label=None):
		""" Create if nessessary or get the existing datafield object with name 'name' and return it.
			If created, attributes 'type' and 'label' are applied to new datafield."""
		f=self.getField(name)
		if f: return f
		return self.addChild(node=DataField(name,None,typ,0,label))
	def asDict(self):
		""" Represent dataitem as simple dictionary mapping of datafield names to their values."""
		ret={}
		for field in self.getTags('field'):
			name=field.getAttr('var')
			typ=field.getType()
			if isinstance(typ,(str,unicode)) and typ[-6:]=='-multi':
				val=[]
				for i in field.getTags('value'): val.append(i.getData())
			else: val=field.getTagData('value')
			ret[name]=val
		if self.getTag('instructions'): ret['instructions']=self.getInstructions()
		return ret
	def __getitem__(self,name):
		""" Simple dictionary interface for getting datafields values by their names."""
		item=self.getField(name)
		if item: return item.getValue()
		raise IndexError('No such field')
	__setitem__ = lambda self, name, val: self.setField(name).setValue(val)
	""" Simple dictionary interface for setting datafields values by their names."""

class DataItem(Node):
	""" This class is used in the DataForm class to describe data items which are used in 'multiple
		item form results' (as described in XEP-0004).
		"""
	def __init__(self,node=None):
		""" Create new empty data item. However, note that, according XEP-0004, DataItem MUST contain ALL
			DataFields described in DataReported.
			Alternatively other XML object can be passed in as the 'node' parameted to replicate it as a new
			dataitem.
			"""
		Node.__init__(self,'item',node=node)
		if node:
			newkids=[]
			for n in self.getChildren():
				if	n.getName()=='field': newkids.append(DataField(node=n))
				else: newkids.append(n)
			self.kids=newkids
	getField = lambda self, name: self.getTag('field',attrs={'var':name})
	""" Return the datafield object with name 'name' (if exists). """
	def setField(self,name):
		""" Create if nessessary or get the existing datafield object with name 'name' and return it. """
		f=self.getField(name)
		if f: return f
		return self.addChild(node=DataField(name))
	def asDict(self):
		""" Represent dataitem as simple dictionary mapping of datafield names to their values."""
		ret={}
		for field in self.getTags('field'):
			name=field.getAttr('var')
			typ=field.getType()
			if isinstance(typ,(str,unicode)) and typ[-6:]=='-multi':
				val=[]
				for i in field.getTags('value'): val.append(i.getData())
			else: val=field.getTagData('value')
			ret[name]=val
		if self.getTag('instructions'): ret['instructions']=self.getInstructions()
		return ret
	def __getitem__(self,name):
		""" Simple dictionary interface for getting datafields values by their names."""
		item=self.getField(name)
		if item: return item.getValue()
		raise IndexError('No such field')
	__setitem__ = lambda self, name, val: self.setField(name).setValue(val)
	""" Simple dictionary interface for setting datafields values by their names."""

class DataForm(Node):
	""" DataForm class. Used for manipulating dataforms in XMPP.
		Relevant XEPs: 0004, 0068, 0122.
		Can be used in disco, pub-sub and many other applications."""
	def __init__(self, typ=None, data=[], title=None, node=None):
		"""
			Create new dataform of type 'typ'; 'data' is the list of DataReported,
			DataItem and DataField instances that this dataform contains; 'title'
			is the title string.
			You can specify the 'node' argument as the other node to be used as
			base for constructing this dataform.

			title and instructions is optional and SHOULD NOT contain newlines.
			Several instructions MAY be present.
			'typ' can be one of ('form' | 'submit' | 'cancel' | 'result' )
			'typ' of reply iq can be ( 'result' | 'set' | 'set' | 'result' ) respectively.
			'cancel' form can not contain any fields. All other forms contains AT LEAST one field.
			'title' MAY be included in forms of type "form" and "result"
		"""
		Node.__init__(self,'x',node=node)
		if node:
			newkids=[]
			for n in self.getChildren():
				if   n.getName()=='field': newkids.append(DataField(node=n))
				elif n.getName()=='item': newkids.append(DataItem(node=n))
				elif n.getName()=='reported': newkids.append(DataReported(node=n))
				else: newkids.append(n)
			self.kids=newkids
		if typ: self.setType(typ)
		self.setNamespace(NS_DATA)
		if title: self.setTitle(title)
		if type(data)==type({}):
			newdata=[]
			for name in data.keys(): newdata.append(DataField(name,data[name]))
			data=newdata
		for child in data:
			if type(child) in [type(''),type(u'')]: self.addInstructions(child)
			elif child.__class__.__name__=='DataField': self.kids.append(child)
			elif child.__class__.__name__=='DataItem': self.kids.append(child)
			elif child.__class__.__name__=='DataReported': self.kids.append(child)
			else: self.kids.append(DataField(node=child))
	getType = lambda self: self.getAttr('type')
	""" Return the type of dataform. """
	setType = lambda self, typ: self.setAttr('type',typ)
	""" Set the type of dataform. """
	getTitle = lambda self: self.getTagData('title')
	""" Return the title of dataform. """
	setTitle = lambda self, text: self.setTagData('title',text)
	""" Set the title of dataform. """
	getInstructions = lambda self: self.getTagData('instructions')
	""" Return the instructions of dataform. """
	setInstructions = lambda self, text: self.setTagData('instructions',text)
	""" Set the instructions of dataform. """
	addInstructions = lambda self, text: self.addChild('instructions',{},[text])
	""" Add one more instruction to the dataform. """
	getField = lambda self, name: self.getTag('field',attrs={'var':name})
	""" Return the datafield object with name 'name' (if exists). """
	def setField(self,name):
		""" Create if nessessary or get the existing datafield object with name 'name' and return it. """
		f=self.getField(name)
		if f: return f
		return self.addChild(node=DataField(name))
	def asDict(self):
		""" Represent dataform as simple dictionary mapping of datafield names to their values."""
		ret={}
		for field in self.getTags('field'):
			name=field.getAttr('var')
			typ=field.getType()
			if isinstance(typ,(str,unicode)) and typ[-6:]=='-multi':
				val=[]
				for i in field.getTags('value'): val.append(i.getData())
			else: val=field.getTagData('value')
			ret[name]=val
		if self.getTag('instructions'): ret['instructions']=self.getInstructions()
		return ret
	def __getitem__(self,name):
		""" Simple dictionary interface for getting datafields values by their names."""
		item=self.getField(name)
		if item: return item.getValue()
		raise IndexError('No such field')
	__setitem__ =  lambda self, name, val: self.setField(name).setValue(val)
	""" Simple dictionary interface for setting datafields values by their names."""
